package org.jeecg.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.system.entity.SysRoleApp;
import org.jeecg.modules.system.entity.SysRolePermission;
import org.jeecg.modules.system.service.ISysRoleAppService;
import org.jeecg.modules.system.vo.SysRoleRelateAppVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static org.jeecg.modules.system.entity.SysRoleApp.buildSysRoleApp;

/**
 * 角色应用关系表
 *
 * @Description: 角色应用关系表
 * @Version: V1.0
 */
@RestController
@RequestMapping("/sys/roleApp")
@Slf4j
@Api(tags = "角色-应用关系")
public class SysRoleAppController extends JeecgController<SysRoleApp, ISysRoleAppService> {
    @Autowired
    private ISysRoleAppService sysRoleAppService;

    @Autowired
    private BaseCommonService baseCommonService;



    /**
     * 查询角色授权
     *
     * @return
     */
    @RequestMapping(value = "/queryRoleApp", method = RequestMethod.GET)
    @ApiOperation(value = "查询角色关联的应用", notes = "查询角色关联的应用")
    public Result<List<String>> queryRoleApp(@RequestParam(name = "roleId", required = true) String roleId) {
        Result<List<String>> result = new Result<>();
        try {
            List<SysRoleApp> list = sysRoleAppService.list(new QueryWrapper<SysRoleApp>().lambda().eq(SysRoleApp::getRoleId, roleId));
            result.setResult(list.stream().map(sra -> String.valueOf(sra.getAppId())).collect(Collectors.toList()));
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 分页列表查询
     *
     * @param sysRoleApp
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "角色应用关系表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<SysRoleApp>> queryPageList(SysRoleApp sysRoleApp,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                   HttpServletRequest req) {
        QueryWrapper<SysRoleApp> queryWrapper = QueryGenerator.initQueryWrapper(sysRoleApp, req.getParameterMap());
        Page<SysRoleApp> page = new Page<SysRoleApp>(pageNo, pageSize);
        IPage<SysRoleApp> pageList = sysRoleAppService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param sysRoleApp
     * @return
     */
    @AutoLog(value = "角色应用关系表-添加")
    @RequiresPermissions("aaa:sys_role_app:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody SysRoleApp sysRoleApp) {
        sysRoleAppService.save(sysRoleApp);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param sysRoleApp
     * @return
     */
    @AutoLog(value = "角色应用关系表-编辑")
    @RequiresPermissions("aaa:sys_role_app:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody SysRoleApp sysRoleApp) {
        sysRoleAppService.updateById(sysRoleApp);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "角色应用关系表-通过id删除")
    @RequiresPermissions("aaa:sys_role_app:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        sysRoleAppService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "角色应用关系表-批量删除")
    @RequiresPermissions("aaa:sys_role_app:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.sysRoleAppService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "角色应用关系表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<SysRoleApp> queryById(@RequestParam(name = "id", required = true) String id) {
        SysRoleApp sysRoleApp = sysRoleAppService.getById(id);
        if (sysRoleApp == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sysRoleApp);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param sysRoleApp
     */
    @RequiresPermissions("aaa:sys_role_app:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SysRoleApp sysRoleApp) {
        return super.exportXls(request, sysRoleApp, SysRoleApp.class, "角色应用关系表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("aaa:sys_role_app:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SysRoleApp.class);
    }


    /**
     * 保存 应用授权
     *
     * @return
     */
    @RequestMapping(value = "/saveRoleAppPermission", method = RequestMethod.POST)
    //@RequiresPermissions("system:permission:saveRole")
    @Transactional
    @ApiOperation(value = "配置角色的关联应用",notes = "配置角色的关联应用")
    public Result<String> saveRoleAppPermission(@RequestBody SysRoleRelateAppVo sysRoleRelateAppVo) {
        long start = System.currentTimeMillis();
        Result<String> result = new Result<>();
        try {
            String roleId = sysRoleRelateAppVo.getRoleId();
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            LambdaQueryWrapper<SysRoleApp> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysRoleApp::getRoleId, roleId);
            this.sysRoleAppService.remove(queryWrapper);
            if (CollectionUtils.isNotEmpty(sysRoleRelateAppVo.getAppIdList())) {
                List<SysRoleApp> sysRoleApps = new ArrayList<>();
                for (int i = 0; i < sysRoleRelateAppVo.getAppIdList().size(); i++) {
                    sysRoleApps.add(buildSysRoleApp(sysRoleRelateAppVo, i, roleId, loginUser, sysRoleApps));
                }
                this.sysRoleAppService.saveBatch(sysRoleApps);
            }
            baseCommonService.addLog("更新角色 " + roleId + "关联的应用，操作人： " + loginUser.getUsername(),
                    CommonConstant.LOG_TYPE_2, 2);
            result.success("保存成功！");
            log.info("======角色授权成功=====耗时:" + (System.currentTimeMillis() - start) + "毫秒");
        } catch (Exception e) {
            result.error500("授权失败！");
            log.error(e.getMessage(), e);
        }
        return result;
    }


}
